package iot

import (
	"errors"
	"gorm.io/gorm"
	"iot-base/common/dbobj"
)

type (
	// ThingParams 设备参数.
	ThingParams dbobj.ThingParam

	ThingParamsModel struct {
		db *gorm.DB
	}
)

func NewThingParamsModel(db *gorm.DB) *ThingParamsModel {
	return &ThingParamsModel{
		db,
	}
}

func (t *ThingParamsModel) GetParams(thingId string) ([]ThingParams, error) {
	var result []ThingParams
	err := t.db.Where("thing_id = ?", thingId).Find(&result).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		return result, err
	}
	return append([]ThingParams{}, result...), nil
}

// BatchInsert 批量插入.
func (t *ThingParamsModel) BatchInsert(params []ThingParams) error {
	return t.db.Model(&ThingParams{}).CreateInBatches(params, 100).Error
}

func (t *ThingParamsModel) DeleteMap(param map[string]interface{}) error {
	return t.db.Where(param).Delete(&ThingParams{}).Error
}
